<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :maskClosable="false"
  >
    <BasicForm @register="registerForm" autoComplete="off" style="margin-top: 1rem" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { accountFormSchema } from './user.data';
  import { getDeptList } from '@/api/system/department';
  import { addUser, updateUser } from '@/api/system/user';
  import { CreateUserParams, UpdateUserParams } from '@/api/system/model/systemModel';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useI18n } from '@/hooks/web/useI18n';

  defineOptions({ name: 'AccountModal' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  const rowId = ref('');
  const { createMessage } = useMessage();
  const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
    baseRowStyle: { 'padding-right': '30px' },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    }

    const treeData = await getDeptList({ status: 1 });
    updateSchema([
      {
        field: 'password',
        show: !unref(isUpdate),
      },
      {
        field: 'dept_id',
        componentProps: { treeData },
      },
    ]);
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  async function handleSubmit() {
    try {
      const { t } = useI18n();
      const values = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      console.log(values);
      if (unref(isUpdate)) {
        console.log('update');
        let params: UpdateUserParams = {
          nickname: values['nickname'],
          username: values['username'],
          password: values['password'],
          role_id: values['role_id'],
          dept_id: values['dept_id'],
          email: values['email'],
          mobile: values['mobile'],
          remark: values['remark'],
        };
        const { code, message } = await updateUser(Number(rowId.value), params);
        if (code == 0) {
          createMessage.success(t('sys.api.updateSuccess'), 1, () => {
            emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
            closeModal();
          });
        } else {
          createMessage.error(message);
        }
      } else {
        let params: CreateUserParams = {
          nickname: values['nickname'],
          username: values['username'],
          password: values['password'],
          role_id: values['role_id'],
          dept_id: values['dept_id'],
          email: values['email'],
          mobile: values['mobile'],
          remark: values['remark'],
        };

        const res = await addUser(params);
        if (res['code'] == 0) {
          createMessage.success(t('sys.api.createSuccess'), 1, () => {
            emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
            closeModal();
          });
        } else {
          createMessage.success(res['message']);
        }
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
